﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Site.Areas.User.ViewModels;
using SDT.Model;
using SDT.Site.Models;
using SDT.Lib.Paging;
using SDT.Lib.Common;
using SDT.Site.Properties;
using System.IO;
using System.Web.Security;
using SDT.Site.Controllers;
using SDT.Lib.MvcMembership;
using System.Linq.Dynamic;
namespace SDT.Site.Areas.User.Controllers
{
    [Authorize]
    public class ProductController : Controller
    {
        public SDTDataContext eDataContext = new SDTDataContext();
        
        public ActionResult Index(int id,int? page)
        {
            if (page == null) page = 1;
            MembershipUser newUser = Membership.GetUser(User.Identity.Name);
            Guid userId = (Guid)newUser.ProviderUserKey;

            var order = UserState.getUserStateFromRequest("userProduct.orderColumn", "order", "ID").ToString();                 // Created by VietLV (Sort data - 05/08/2011)
            var orderDir = UserState.getUserStateFromRequest("userProduct.orderDirColumn", "orderDir", "desc").ToString();         // Created by VietLV (Sort data - 05/08/2011)

            int pageSize = int.Parse(UserState.getUserStateFromRequest("userProduct.pageSize", "PageSize", 10).ToString());
            var db = new SDTDataContext();
            var a = new ProductViewModel();

            //var data = db.Products
            //                .Where(d => id > 0 ? d.TypeID == id : true)
            //                .Where(d => d.AddBy.Equals(userId)).OrderByDescending(d => d.ID);
            a.Products = db.Products
                            .Where(d => id > 0 ? d.TypeID == id : true)
                            .Where(d => d.AddBy.Equals(userId))
                            .OrderBy(string.Format("{0} {1}", order, orderDir))                                            // Created by VietLV (Sort data - 05/08/2011)
                            .ToPagedList(page.Value - 1, pageSize);
            ViewData["order"] = order;
            ViewData["orderDir"] = orderDir;
            var stringTitle = id == 1 ? "Danh sách tin rao bán" : "Dánh sách tin cho thuê";
            ViewData["stringTitle"] = stringTitle;
            return View(a);
        }

        #region GET: /Product/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                // product detail
                Product pro = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();

                // product category
                List<ProductCategory> categories = eDataContext.ProductCategories
                                                .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                .ToList();

                // city
                List<SelectListItem> listC = eDataContext.Cities
                                                .Select(c => new SelectListItem()
                                                {
                                                    Value = c.ID.ToString(),
                                                    Text = c.Name
                                                }).ToList();

                // district
                List<SelectListItem> listD = eDataContext.Districts
                                                .Where(d => d.CityID == pro.CityID)
                                                .Select(d => new SelectListItem()
                                                {
                                                    Value = d.ID.ToString(),
                                                    Text = d.Name
                                                }).ToList();

                // product attribute
                var listPAtt = eDataContext.ProductAttributes.ToList();

                // product attribute value
                var listPAttID = eDataContext.ProductAttributeValues.Where(pV => pV.ProductID == id).Select(pV => pV.AttributeID).ToList();

                // product image
                List<string> listF = pro.AddDate != null ? Uploads.GetFile(id, Settings.Default.SiteRootPath, Settings.Default.ProductRootPath, Settings.Default.ProductFormatSubPath, pro.AddDate.Value) : null; // Modified by Vietlv (isert confident pro.AddDate = null)
                // List Direction
                var listDirection = Utils.StringToDictionary(Settings.Default.ProductDirection.ToString(), ",");
                var currentDirection = "";
                foreach (var itemDirection in listDirection)
                {
                    var itemKey = Convert.ToInt32(itemDirection.Key);
                    if (pro.Direction != null && itemKey == int.Parse(pro.Direction)) currentDirection = itemDirection.Value.ToString();
                }
                return View(new ProductInputModel
                {
                    Categories = categories,
                    ListCity = listC,
                    Product = pro,
                    ListDistrict = listD,
                    CityID = pro.CityID,
                    DistrictID = pro.DistrictID,
                    CatID = pro.CatID,
                    TypeID = pro.TypeID,
                    ListProductAtribute = listPAtt,
                    ListProductAttributeID = listPAttID,
                    ListFile = listF,
                    CurrentDirection = currentDirection,
                    ImageRootUrl = Settings.Default.SiteRootUrl
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Product/Create
        public ActionResult Create()
        {
            try
            {
                MembershipUser newUser = Membership.GetUser(User.Identity.Name);
                Guid userId = (Guid)newUser.ProviderUserKey;
                List<SelectListItem> listC = eDataContext.Cities
                                                .Select(c => new SelectListItem()
                                                {
                                                    Value = c.ID.ToString(),
                                                    Text = c.Name
                                                }).ToList();
                var listPAtt = eDataContext.ProductAttributes.ToList();
                List<SelectListItem> listType = eDataContext.ProductTypes
                                                .Select(t => new SelectListItem()
                                                {
                                                    Text = t.Name,
                                                    Value = t.ID.ToString()
                                                }).ToList();

                // Created by Vietlv
                // Created date: 29/07/2011
                // Description: Select list ProductDirection, ProductExpire  of product
                var listProductDirection = Utils.StringToDictionary(Settings.Default.ProductDirection.ToString(), ",");
                var listProductExpire = Utils.StringToDictionary(Settings.Default.ProducExpire.ToString(), ",");
                var listCurrency = Utils.StringToDictionary(Settings.Default.ListCurrency.ToString(), ",");
                var listUnitCost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",");
                var usermanager = UserManager.GetUser(UserManager.GetUserId(), true);

                return View(new ProductInputModel
                {
                    ListCity = listC,
                    ListProductAtribute = listPAtt,
                    ListType = listType,
                    listProductDirection = listProductDirection,
                    listProductExpire = listProductExpire,
                    ListCurrency = listCurrency,
                    ListUnitCost = listUnitCost

                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Product/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ProductInputModel m)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UpdateModel(m);
                    var exDate = Convert.ToInt32(Request["ExpireDateTime"]);

                    m.Product.ExpireDate = DateTime.Now.AddDays(exDate);
                    m.Product.AddBy = UserManager.GetUserId();
                    m.Product.AddDate = DateTime.Now;
                    #region cost convert
                    // Case currency is "VND"
                    if (m.Product.CurrencyID == 1)
                    {
                        //Case unit cost is VND/m2
                        if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                     // from  m.Product.UnitCost = costTypeID + new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2)  
                        }                                                                                             // To m.Product.UnitCost =new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2);   
                        // Case unit cost is VND/m2/tháng
                        if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            //var ttCost = Convert.ToDecimal(Request["Product.Cost"]);
                            m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        // Case unit cost is VND/tổng diện tích
                        if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = m.Product.Cost;
                        }
                        m.Product.CurrencyName = "VND";
                    }
                    // Case currency is "USD"
                    if (m.Product.CurrencyID == 2)
                    {
                        //Case unit cost is USD/m2
                        if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost.Value;
                        }
                        // Case unit cost is USD/m2/tháng
                        if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        //Case unit cost is USD/Tổng
                        if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Cost.Value;
                        }
                        m.Product.CurrencyName = "USD";
                    }

                    if (m.Product.TotalCost.HasValue)
                    {
                        //Binhlv Lay ConvertPriceID Phu hop
                        // string conPri = (m.Product.TotalCost.Value / int.Parse(Settings.Default.UnitConvert)).ToString();
                        m.Product.ConvertPrice1 = GetConvertPrice(m.Product.TotalCost.Value, m.Product.TypeID);//byte.Parse(conPri.Substring(0, conPri.IndexOf(".")));
                    }
                    //Binhlv
                    // Khoang dien tich
                    if (m.Product.Area.HasValue)
                    {
                        int typeid = m.Product.TypeID;
                        var area = m.Product.Area.Value;
                        m.Product.ConvertArea1 = GetConvertArea(area, typeid);
                    }
                    #endregion

                    eDataContext.Products.InsertOnSubmit(m.Product);
                    eDataContext.SubmitChanges();

                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Product.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProductRootPath), "" + m.Product.ID);
                    }
                    eDataContext.SubmitChanges();

                    #region product attribute
                    List<short> listProductAttributeID = Request["ProductAttributeValue"].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(i => short.Parse(i)).ToList();
                    foreach (short id in listProductAttributeID)
                    {
                        ProductAttributeValue proAttValue = new ProductAttributeValue();

                        proAttValue.AttributeID = id;
                        proAttValue.ProductID = m.Product.ID;
                        proAttValue.Value = "1";

                        eDataContext.ProductAttributeValues.InsertOnSubmit(proAttValue);
                        eDataContext.SubmitChanges();
                    }

                    #endregion

                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ImagePaths")
                        {
                            string filePath = string.Empty;
                            string subPath = string.Format(Settings.Default.ProductFormatSubPath, m.Product.AddDate.Value.Year, m.Product.AddDate.Value.Month, m.Product.AddDate.Value.Day, m.Product.ID);
                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath);
                            }
                            filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, file.FileName);
                            file.SaveAs(filePath);
                        }
                    }
                    #endregion

                    return RedirectToAction("Index", "Product");
                }
                else
                {
                    throw new Exception("Dữ liệu nhập không đúng.");
                }
            }
            catch (Exception exp)
            {
                if (exp.Message.Contains("out of range"))  // Vietlv
                {
                    ViewData[Messages.MessageInfo] = "Tổng giá trị của bất động sản đã vượt quá mức con số cho phép. Vui xem xét lại!";
                    return View();
                }
                ViewData[Messages.MessageInfo] = exp.Message;
                return RedirectToAction("Index", "User/Product");
            }
        }
        #endregion

        #region Diep/ GetConvertPrice
        private ConvertPrice GetConvertPrice(decimal TotalPrice, int TypeProduct)
        {
            try
            {
                if (TotalPrice < 0) throw new NotSupportedException();
                var maxArea = eDataContext.ConvertPrices
                    .Where(e => e.TypeID == TypeProduct)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (TotalPrice > maxArea.MaxValue)
                {
                    return maxArea;
                }
                var CurrentConvertPrice = eDataContext.ConvertPrices
                                        .Where(ca => ca.TypeID == TypeProduct)
                                        .Where(c => c.MinValue < TotalPrice && c.MaxValue >= TotalPrice) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertPrice;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Diep/GetConvertAreaID
        private ConvertArea GetConvertArea(double Area, int TypeProduct)
        {
            try
            {
                if (Area < 0) throw new NotSupportedException();
                var maxArea = eDataContext.ConvertAreas
                    .Where(e => e.TypeID == TypeProduct)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (Area > Convert.ToDouble(maxArea.MaxValue))
                {
                    return maxArea;
                }
                var CurrentConvertAreaID = eDataContext.ConvertAreas
                                        .Where(ca => ca.TypeID == TypeProduct)
                                        .Where(c => c.MinValue < (decimal)Area && c.MaxValue >= (decimal)Area) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertAreaID;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region GET: /Product/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                MembershipUser newUser = Membership.GetUser(User.Identity.Name);
                Guid userId = (Guid)newUser.ProviderUserKey;
                // product detail
                Product pro = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();
                

                if (!pro.AddBy.Equals(userId)) return RedirectToAction("Index");
                // product category
                List<ProductCategory> categories = eDataContext.ProductCategories
                                                .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                .ToList();

                // city
                List<SelectListItem> listC = eDataContext.Cities
                                                .Select(c => new SelectListItem()
                                                {
                                                    Value = c.ID.ToString(),
                                                    Text = c.Name
                                                }).ToList();

                // district
                List<SelectListItem> listD = eDataContext.Districts
                                                .Where(d => d.CityID == pro.CityID)
                                                .Select(d => new SelectListItem()
                                                {
                                                    Value = d.ID.ToString(),
                                                    Text = d.Name
                                                }).ToList();

                // product attribute
                var listPAtt = eDataContext.ProductAttributes.ToList();

                // product attribute value
                var listPAttID = eDataContext.ProductAttributeValues.Where(pV => pV.ProductID == id).Select(pV => pV.AttributeID).ToList();

                // product type
                List<SelectListItem> listType = eDataContext.ProductTypes
                                                .Select(t => new SelectListItem()
                                                {
                                                    Text = t.Name,
                                                    Value = t.ID.ToString()
                                                }).ToList();

                // product image
                List<string> listF = Uploads.GetFile(id, Settings.Default.SiteRootPath, Settings.Default.ProductRootPath, Settings.Default.ProductFormatSubPath, pro.AddDate.Value);

                // Created by VietLV (28/07/2011) (get current CostType)
                //var isUSD = pro.UnitCost.Contains("USD");                    
                //var currentCostType = isUSD == true ? "USD" : "VND";
                //var currentUnistCost = pro.UnitCost.Contains("/m2/tháng") == true ? "M2M" : (pro.UnitCost.Contains("/tổng") == true ? "SUM" : "M2");
                var listCurrency = Utils.StringToDictionary(Settings.Default.ListCurrency.ToString(), ",");
                var listUnitCost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",");
                var listExpireDate = Utils.StringToDictionary(Settings.Default.ProducExpire.ToString(), ",");
                var listDirection = Utils.StringToDictionary(Settings.Default.ProductDirection.ToString(), ",");
               
                return View(new ProductInputModel
                {
                    Categories = categories,
                    ListCity = listC,
                    Product = pro,
                    ListDistrict = listD,
                    CityID = pro.CityID,
                    DistrictID = pro.DistrictID,
                    CatID = pro.CatID,
                    TypeID = pro.TypeID,
                    ListProductAtribute = listPAtt,
                    ListProductAttributeID = listPAttID,
                    ListType = listType,
                    ListFile = listF,
                    ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl,
                    ListCurrency = listCurrency,
                    ListUnitCost = listUnitCost,
                    listProductExpire = listExpireDate,
                    listProductDirection = listDirection,
                    
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return RedirectToAction("Index", "User/Product");
            }
        }
        #endregion

        #region POST: /Product/Edit/5
        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, ProductInputModel m)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    m.Product = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();
                    if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                    eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    UpdateModel(m);

                    #region cost convert

                    #region Case currency is "VND"
                    if (m.Product.CurrencyID == 1)
                    {
                        //Case unit cost is VND/m2
                        if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                     // from  m.Product.UnitCost = costTypeID + new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2)  
                        }                                                                                             // To m.Product.UnitCost =new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2);   
                        // Case unit cost is VND/m2/tháng
                        if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            //var ttCost = Convert.ToDecimal(Request["Product.Cost"]);
                            m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        // Case unit cost is VND/tổng
                        if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = m.Product.Cost;
                        }
                        m.Product.CurrencyName = "VND";
                    }
                    #endregion

                    #region Case currency is "USD"
                    if (m.Product.CurrencyID == 2)
                    {
                        //Case unit cost is USD/m2
                        if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost.Value;
                        }
                        // Case unit cost is USD/m2/tháng
                        if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        //Case unit cost is USD/Tổng
                        if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                            }
                            m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Cost.Value;
                        }
                        m.Product.CurrencyName = "USD";
                    }
                    #endregion
                    eDataContext.SubmitChanges();
                    if (m.Product.TotalCost.HasValue)
                    {
                        //Binhlv 
                        m.Product.ConvertPrice1 = GetConvertPrice(m.Product.TotalCost.Value, m.Product.TypeID);
                        //string conPri = (m.Product.TotalCost.Value / 1000000000).ToString();
                        //m.Product.ConvertPrice = byte.Parse(conPri.Substring(0, conPri.IndexOf(".")));
                    }
                    //Binhlv
                    // Khoang dien tich
                    if (m.Product.Area.HasValue)
                    {
                        m.Product.ConvertArea1 = GetConvertArea(m.Product.Area.Value, m.Product.TypeID);
                    }
                    #endregion
                    int exDate = Utils.ParseInt(Request["ExpireNumber"].ToString());
                    if (exDate > 0) m.Product.ExpireDate=m.Product.ExpireDate.Value.AddDays(exDate);
                    m.Product.ModifyBy = UserManager.GetUserId();
                    m.Product.ModifyDate = DateTime.Now;

                    eDataContext.SubmitChanges();

                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Product.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProductRootPath), "" + m.Product.ID);
                    }
                    eDataContext.SubmitChanges();

                    #region product attribute

                    var pAtt = eDataContext.ProductAttributeValues.Where(pa => pa.ProductID == id).ToList();
                    eDataContext.ProductAttributeValues.DeleteAllOnSubmit(pAtt);
                    eDataContext.SubmitChanges();

                    ///Modified by Vietlv
                    ///Modified date: 27/08/2011
                    ///Description manage map Product with ProductAttribute
                    // Delete attribute olde
                    var listProAttribute = eDataContext.ProductAttributeValues.Where(e => e.ProductID == id).ToList();
                    eDataContext.ProductAttributeValues.DeleteAllOnSubmit(listProAttribute);
                    // insert new attribute to table ProductAttributeValue
                    foreach (var proAtt in eDataContext.ProductAttributes)
                    {
                        var isSelected = Request["ProductAtribute." + proAtt.ID] != null && Request["ProductAtribute." + proAtt.ID].ToString().Equals("false") == false ? true : false;
                        if (isSelected == true)
                        {
                            var itemAttribute = new ProductAttributeValue();
                            itemAttribute.ProductID = id;
                            itemAttribute.AttributeID = proAtt.ID;
                            itemAttribute.Value = "1";
                            eDataContext.ProductAttributeValues.InsertOnSubmit(itemAttribute);
                        }
                    }
                    eDataContext.SubmitChanges();
                    #endregion

                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                        {
                            string filePath = string.Empty;
                            string subPath = string.Format(Settings.Default.ProductFormatSubPath, m.Product.AddDate.Value.Year, m.Product.AddDate.Value.Month, m.Product.AddDate.Value.Day, m.Product.ID);
                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath);
                            }
                            filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, file.FileName);
                            file.SaveAs(filePath);
                        }
                    }
                    #endregion
                    eDataContext.Transaction.Commit();
                    eDataContext.Transaction.Dispose();
                  //  eDataContext.Connection.Close();
                    return RedirectToAction("Index", "Product");
                }
                else
                {
                    throw new Exception("Dữ liệu nhập không đúng.");

                }
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                if (exp.Message.Contains("out of range"))
                {
                    ViewData[Messages.MessageInfo] = "Tổng giá trị của bất động sản đã vượt quá mức con số cho phép. Vui xem xét lại!";
                    return View();
                }
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
            
        }
        public ActionResult Delete(int id)
        {
            try
            {
                Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id && e.AddBy==UserManager.GetUserId());
                if (pro == null) {
                    ViewData[Messages.MessageInfo] = Messages.ERR_PRD_001;
                }
                return View(pro);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id && e.AddBy == UserManager.GetUserId());
                if (pro != null)
                {
                    string subPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, pro.ID);
                    string subThumbPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, "Thumb\\" + pro.ID);
                    if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                    {
                        // If it doesn't then we just create it before going any further
                        Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath,true);
                    }
                    if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath))
                    {
                        // If it doesn't then we just create it before going any further
                        Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath, true);
                    }
                    eDataContext.CommentsInProducts.DeleteAllOnSubmit(from e in eDataContext.CommentsInProducts where e.ProductID == id select e); 
                    eDataContext.Products.DeleteOnSubmit(pro);

                    eDataContext.SubmitChanges();
                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
        /// <summary>
        /// Add by: Vietlv
        /// AddDate: 06/08/2011
        /// </summary>
        /// <returns></returns>
        private readonly IUserService _userService;
        private readonly IPasswordService _passwordService;

        public ProductController()
			: this (
				new AspNetMembershipProviderWrapper(Membership.Provider),
            new AspNetMembershipProviderWrapper(Membership.Provider)){}
        public SDTDataContext db = new SDTDataContext();
        public ProductController(
			IUserService userService,
            IPasswordService passwordService)
		{
			_userService = userService;
            _passwordService = passwordService;
		}
    }
     
}
